class WorkItem < ActiveRecord::Base

  belongs_to :work_item_type
  belongs_to :stage
  has_many :designer_work_items, :dependent => :destroy

  validates_presence_of :name,
    :work_item_type_id,
    :stage_id
  validates_uniqueness_of :name,
    :scope => [:work_item_type_id, :stage_id]  
  validates_numericality_of :pay_unit,
    :greater_than_or_equal_to => 0

  def total_amount
    DesignerWorkItem.sum(:should_be_payed, :conditions => { :work_item_id => id})
  end

  def self.should_be_payed(args = {})
    DesignerWorkItem.sum(:should_be_payed,
      :conditions => [
        ' work_item_type_id = :work_item_type_id and stage_id = :stage_id',
        args
      ]
    )
  end
  
  def should_be_payed
    DesignerWorkItem.sum(:should_be_payed,
      :conditions => [
        ' work_item_id = ?',
        id
      ]
    )
  end

  def allowance?
    name == '补贴'
  end

  def after_save
    designer_work_items.each do |designer_work_item|
      designer_work_item.reset_should_be_payed!
      designer_work_item.save!
    end
  end

  def after_destroy
    stage.reset_should_be_payed!
    stage.save!
    stage.project.reset_stat!
    stage.project.save!
  end
  
  def designer_work_items_by_stage_id(stage_id)
    DesignerWorkItem.find_all_by_stage_id_and_work_item_id(stage_id,id)
  end

end
